//引入安装的axios插件
import axios from "axios";
import {removeToken, getToken, removeUserInfo} from "./auth";
import store from "../store";
import {Message} from "element-ui";
import router from "@/router";
import {JSEncrypt} from "jsencrypt";
import api from '../api';

//加密公钥
let publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtJy0nsaFOfaeU/lxysrT\n' +
    '0Eo5qlNJnWYJG1BxwuUOJqRz2uvsLeuK6KiBM4LdTpuKkW37nh8RaHM2XG3ynPPv\n' +
    'LiGdxx2C7/wm7fjojycCj1fQWPQwwv9kmHyc0y4WgHsjpKM5sPp1VgrIyWpDbLdi\n' +
    'D4+6+yanhe272vgCcsuA/KZoDvRyVN3p8TZjIh35eBKOssd/vf7DwGZ1Xhdw8SXr\n' +
    '6ONJ/GUjkXbZBkOwhaGYCbF1M1Fk5lvYSkHbd7S0Cm1qYagmRRgECWv1JRaKS3+5\n' +
    '7q7TvcocFcMJxQlm/aKkWi/jIsTQdkkUKU0i4OiawaxKn2W/hgn9fceGQQ0B/kdV\n' +
    '5wIDAQAB'

//生成实例
const service = axios.create({
    // baseURL: 'https://localhost:8800/timeapi',
    baseURL: 'http://localhost:8081/timeapi',
    // baseURL: 'http://192.168.74.129:8081/timeapi',
    timeout: 9000000,
});

// 请求拦截，在请求前在headers中加入TOKEEN，TOKEN来自COOKIE
service.interceptors.request.use(
    (config) => {
        //修改请求参数加密
        console.log(JSON.parse(JSON.stringify(config)),"config")
        if (!config.url.includes("main/upload") && !config.url.includes("main/largeFilSlicingUpload") && config.url.includes("loginserviceapi")) {
            if (config.data) {
                config.data = RSAEncrypt(config.data, publicKey)
            } else if (config.params) {
                config.params = {encryptData: RSAEncrypt(config.params, publicKey)}
            }
        }
        // console.log(JSON.parse(JSON.stringify(config)),"config")
        //添加请求头
        let token = getToken();
        if (token) {
            config.headers["Authorization"] = "Bearer " + token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

//加密方法
function RSAEncrypt(pas, publicKey) {
    //实例化jsEncrypt对象
    let jse = new JSEncrypt();
    let obj = removeEmptyFields(pas)
    //设置公钥
    jse.setPublicKey(publicKey);
    return encodeURIComponent(jse.encrypt(JSON.stringify(obj)));
}

/**
 * 移除空字段
 * @param obj
 * @returns {*}
 */
function removeEmptyFields(obj) {
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const value = obj[key];

            // 判断是否为空
            if (
                value === null ||
                value === '' ||
                (Array.isArray(value) && value.length === 0) ||
                (typeof value === 'object' && Object.keys(value).length === 0)
            ) {
                delete obj[key];
            } else if (typeof value === 'object') {
                // 递归处理嵌套对象
                removeEmptyFields(value);
            }
        }
    }
    return obj;
}

// 返回报文拦截，在接收报文前处理错误情况，如网络错误，无权限等
service.interceptors.response.use(
    (response) => {
        const res = response.data;
        if (res && res.code && res.code != 200) {
            if (res.code == 401) {
                router.replace('/');
                store.commit("app/setUserInfo", null);
                removeToken();
                // location.reload();
                Message.warning("请先登陆！");

            } else if (res.code == 500) {
                Message.error(res.message);
            } else {
                Message.warning(res.message);
            }
        }
        return res;
    },
    async (error) => {
        Message.error("网络异常");
        if (error.message.includes("401")) {
            console.log(error.message)
            api.auth.removeToken();
            api.auth.removeUserInfo();
            api.auth.removeRouters();
            store.commit('app/setRoutes', [])
            store.commit('app/setUserInfo', null)
            router.replace('/')
        }
    }
);
export default service;
